package org.kumas.bigdata.hdfs3.rpc;

import org.kumas.bigdata.hdfs3.fsdirectory.FSDirectory;
import org.kumas.bigdata.hdfs3.protocol.FileSystemProtocol;
import org.kumas.bigdata.hdfs3.serialization.FsSerializations;

import java.io.*;

import static org.kumas.bigdata.hdfs3.fsdirectory.FSDirectory.SNAP_SHOT;

/*************************************************
 * TODO_Kumas
 *  Author： KumasZhang
 *  DateTime： 2021-12-05 10:16
 *  Description： 
 **/
public class FileSystemProtocolImpl implements FileSystemProtocol {
    public static FSDirectory FILE_DIR_SYSTEM = new FSDirectory();

    static {
        loadFileSystem();
    }

    // TODO_Kumas 注释： 冷启动加载到内存
    private static void loadFileSystem() {
        FsSerializations serializations = new FsSerializations();
        synchronized (SNAP_SHOT) {
            if (SNAP_SHOT.exists()) {
                try (
                        FileInputStream fis = new FileInputStream(SNAP_SHOT);
                        BufferedInputStream bis = new BufferedInputStream(fis);
                ) {
                    FILE_DIR_SYSTEM = serializations.deserialize(bis, FILE_DIR_SYSTEM);
                    FILE_DIR_SYSTEM.print();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public Response createFile(String dir, String fileName, byte[] blocks) {
        return FILE_DIR_SYSTEM.createFile(dir, fileName, blocks);
    }

    @Override
    public Response mkdir(String path, boolean recursive) {
        return FILE_DIR_SYSTEM.mkdir(path, recursive);
    }


    @Override
    public Response ls(String path) {
        return FILE_DIR_SYSTEM.ls(path);
    }

    @Override
    public Response cat(String file) {
        return FILE_DIR_SYSTEM.cat(file);
    }

    @Override
    public Response printTree() {
        return FILE_DIR_SYSTEM.print();
    }

}
